package edu.biwu.Response;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/resp/download01")
public class RespDownload01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取filename参数
        String fileName = request.getParameter("fileName");

        //设置MIME和下载响应头
        String mimeType = getServletContext().getMimeType(fileName);
        response.setHeader("Content-Type",mimeType);
        response.setHeader("Content-Disposition","attachment;filename="+fileName);

        //将指定的文件字节写给浏览器
        ServletOutputStream os = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(os);


        InputStream is = getServletContext().getResourceAsStream("/download/" + fileName);
        BufferedInputStream bis = new BufferedInputStream(is);
        int b;
        while ((b=bis.read())!=-1){
            bos.write(b);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
